package org.cloud.core.common.result;

import lombok.Data;

import java.io.Serializable;

/**
 * @author Violet
 * @description 统一返回结果
 * @date 2021/5/20
 * update: 2021/6/13 新增泛型
 */
@Data
public class R<T> implements Serializable {

    private static final long serialVersionUID = 8643295887711828325L;

    private int code;
    private String msg;
    private T result;

    private R() {
    }

    private R(ResultEnum e) {
        this.code = e.getCode();
        this.msg = e.getMsg();
    }

    private R(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private R(ResultEnum e, T result) {
        this.code = e.getCode();
        this.msg = e.getMsg();
        this.result = result;
    }

    public static <T> R<T> success() {
        return new R<>(ResultEnum.SUCCESS);
    }

    public static <T> R<T> success(T data) {
        return new R<>(ResultEnum.SUCCESS, data);
    }

    public static <T> R<T> fail() {
        return new R<>(ResultEnum.FAIL);
    }

    public static <T> R<T> fail(ResultEnum e) {
        return new R<>(e);
    }

    public static <T> R<T> fail(String msg) {
        return new R<>(ResultEnum.FAIL.getCode(), msg);
    }

    public static <T> R<T> isSuccess(boolean condition) {
        return condition ? success() : fail();
    }

    public static <T> R<T> isSuccess(boolean condition, T data) {
        return condition ? success(data) : fail();
    }
}
